package com.itheima.travel.service.impl;

import com.itheima.travel.mapper.UserMapper;
import com.itheima.travel.pojo.User;
import com.itheima.travel.pojo.UserExample;
import com.itheima.travel.req.UserVo;
import com.itheima.travel.service.UserService;
import com.itheima.travel.session.SubjectUser;
import com.itheima.travel.session.SubjectUserContext;
import com.itheima.travel.utils.BeanConv;
import com.itheima.travel.utils.EmptyUtil;
import com.itheima.travel.utils.MD5Coder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

@Service
//处理业务逻辑
public class UserServiceImpl implements UserService {
    //注入
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SubjectUserContext subjectUserContext;
    //注册
    @Override
    public Boolean registerUser(UserVo userVo) {
        //将service层的vo对象转为dao层能识别的pojo对象
        User user = BeanConv.toBean(userVo, User.class);
        //调用dao层对象，对密码用MD5加密
        user.setPassword(MD5Coder.md5Encode(user.getPassword()));
        //返回影响行数
        int i = userMapper.insert(user);
        return i>0;
    }

    //用户登录
    @Override
    public UserVo loginUser(UserVo userVo) {
        //组装条件，放入example例子中
        UserExample userExample = new UserExample();
        //添加条件userExample中的用户名和userVo的用户名一样，密码是加密后的密码
        userExample.createCriteria().
                andUsernameEqualTo(userVo.getUsername()).
                andPasswordEqualTo(MD5Coder.md5Encode(userVo.getPassword()));
        //根据条件查找数据库表中的用户
        List<User> userList = userMapper.selectByExample(userExample);
        //dao层得到的对象是pojo类型的需要转换为vo类型的数据
        List<UserVo> userVoList = BeanConv.toBeanList(userList, UserVo.class);
        UserVo uv=null;
        //判断查询结果，有无值
        if(userVoList.size()==1){//说明登录成功
            //取出这个userVo对象
             uv = userVoList.get(0);
            //登录成功后绑定唯一标识
            String token = UUID.randomUUID().toString();
            uv.setToken(token);
            //将数据保存到session中
            subjectUserContext.createdSubject(token,BeanConv.toBean(uv, SubjectUser.class));
            return uv;
        }
        return uv;
    }

    //退出
    @Override
    public void loginOutUser() {
        //将session删除
        subjectUserContext.deleteSubject();

    }

    //判断是否有用户登录成功
    @Override
    public Boolean isLogin() {
        //从session域中获取
        SubjectUser subject = subjectUserContext.getSubject();
        //判断有无数据
        //若不是空，则返回true
        return !EmptyUtil.isNullOrEmpty(subject);
    }
}
